package com.xb.cloud.usercenter.client;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xb.cloud.common.JsonUtils;
import com.xb.cloud.common.util.DateUtils;
import com.xb.cloud.gateway.client.Adapter;
import com.xb.cloud.gateway.client.AdapterContext;
import com.xb.cloud.gateway.client.ReturnCodes;
import com.xb.cloud.gateway.client.ReturnUtils;
import com.xb.cloud.gateway.client.RtnInfo;
import com.xb.cloud.user.service.client.CheckoutInputBo;
import com.xb.cloud.user.service.client.ShoppingCartItemInputBo;
import com.xb.cloud.usercenter.client.vo.OrderMerchantQueryVo;
import com.xb.cloud.usercenter.service.OrderByMerchantApiService;
import com.xb.cloud.usercenter.service.SellOrderMerchantApiService;

/**
 * 
 * @ClassName: SellOrderMerchantAdapter
 * @Description:商家订单操作
 * @author: 鲜备科技
 * 
 * @Copyright: 2018 www.xianbeitech.com Inc. All rights reserved.
 *
 */
@Component
public class SellOrderMerchantApiAdapter extends Adapter {

	private final Logger logger = LoggerFactory.getLogger(SellOrderMerchantApiAdapter.class);

	@Resource
	SellOrderMerchantApiService sellOrderMerchantApiService;

	@Resource
	OrderByMerchantApiService orderByMerchantApiService;

	/**
	 * 
	 */
	public RtnInfo execute(String urlPath, Boolean isLogined, Map<String, String> bizInfo, AdapterContext context) {
		long time = System.currentTimeMillis();

		RtnInfo rtnInfo = null;
		long companyId = context.getCompanyId();
		long merchantId = context.getCurrentMerchantUserId();

		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("companyId", companyId);
		paramMap.put("merchantId", merchantId);

		if ("/h5/merchant/order/list".equalsIgnoreCase(urlPath)) {
			
			OrderMerchantQueryVo queryVo = new OrderMerchantQueryVo();

			String startTimeString = bizInfo.get("startTime");
			String endTimeString = bizInfo.get("endTime");
			Date startTime = null;
			Date endTime = null;
			if (startTimeString != null ) {
				try {
					startTime = DateUtils.stringToDate(startTimeString, DateUtils.patternA);
					queryVo.setStartTime(startTime);
					if(endTimeString != null) {
						endTime = DateUtils.stringToDate(endTimeString, DateUtils.patternA);
						endTime = DateUtils.addDays(endTime, 1);
						
					} else {
						endTime = new Date();
					}
					queryVo.setEndTime(endTime);
				} catch (Exception e) {
					return ReturnUtils.error(ReturnCodes.STATEMENT_QUERY_DATE_ILLEGAL, "query date illegal");
				}

			}

			// 用户订单列表，分不同类型（订单状态），分页
			int pageNum = Integer.parseInt(bizInfo.get("pageNum"));
			int pageSize = Integer.parseInt(bizInfo.get("pageSize"));
			String status = bizInfo.get("status");

			queryVo.setCompanyId(companyId);
			queryVo.setPageNum(pageNum);
			queryVo.setPageSize(pageSize);
			queryVo.setStatus(status);
			return sellOrderMerchantApiService.getOrderListByStatus(queryVo, merchantId);
		} else if ("/h5/merchant/order/count".equalsIgnoreCase(urlPath)) {
			// 用户订单计数
			String status = bizInfo.get("status");
			OrderMerchantQueryVo queryVo = new OrderMerchantQueryVo();
			queryVo.setCompanyId(companyId);
			queryVo.setStatus(status);

			rtnInfo = sellOrderMerchantApiService.getOrderCountWithStatus(queryVo, merchantId);
		} else if ("/h5/merchant/order/orderDetail".equalsIgnoreCase(urlPath)) {
			// 订单详情
			Long orderId = null;
			/**
			 * 参数验证
			 */
			try {
				orderId = Long.valueOf(bizInfo.get("orderId"));
				if (orderId == null) {
					return RtnInfo.ParameterErrRtnInfo("非法参数错误");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("非法参数错误,入参为:" + bizInfo);
				return RtnInfo.ParameterErrRtnInfo("非法参数错误");
			}

			rtnInfo = sellOrderMerchantApiService.getOrderDetailsById(orderId);
		} else if ("/h5/merchant/order/confirmPay".equalsIgnoreCase(urlPath)) {
			// 确认支付
			Long orderId = null;
			/**
			 * 参数验证
			 */
			try {
				orderId = Long.valueOf(bizInfo.get("orderId"));
				if (orderId == null) {
					return RtnInfo.ParameterErrRtnInfo("非法参数错误");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("非法参数错误,入参为:" + bizInfo);
				return RtnInfo.ParameterErrRtnInfo("非法参数错误");
			}

			rtnInfo = sellOrderMerchantApiService.confirmPay(orderId, merchantId);
		} else if ("/h5/merchant/order/orderDelivery".equalsIgnoreCase(urlPath)) {
			// 发货
			Long orderId = null;
			/**
			 * 参数验证
			 */
			try {
				orderId = Long.valueOf(bizInfo.get("orderId"));
				if (orderId == null) {
					return RtnInfo.ParameterErrRtnInfo("非法参数错误");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("非法参数错误,入参为:" + bizInfo);
				return RtnInfo.ParameterErrRtnInfo("非法参数错误");
			}

			rtnInfo = sellOrderMerchantApiService.orderDelivery(orderId, merchantId);
		} else if ("/h5/merchant/order/cancelOrder".equalsIgnoreCase(urlPath)) {
			// 取消订单
			Long orderId = null;
			Long cancelResaonId = null;
			/**
			 * 参数验证
			 */
			try {
				orderId = Long.valueOf(bizInfo.get("orderId"));
				cancelResaonId = Long.valueOf(bizInfo.get("cancelResaonId"));
				if (orderId == null || cancelResaonId == null) {
					return RtnInfo.ParameterErrRtnInfo("非法参数错误");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("非法参数错误,入参为:" + bizInfo);
				return RtnInfo.ParameterErrRtnInfo("非法参数错误");
			}

			rtnInfo = sellOrderMerchantApiService.orderCancel(orderId, merchantId, cancelResaonId);
		} else if ("/h5/merchant/order/getCancelReasonList".equalsIgnoreCase(urlPath)) {
			// 获取系统取消订单原因列表
			rtnInfo = sellOrderMerchantApiService.getCancelReasonList(companyId);
		} else if ("/h5/merchant/order/createOrder".equalsIgnoreCase(urlPath)) {
			CheckoutInputBo checkoutInputBo = new CheckoutInputBo();
			checkoutInputBo.setCompanyId(companyId);
			checkoutInputBo.setMerchantId(merchantId);
			checkoutInputBo.setUsername(bizInfo.get("username"));
			checkoutInputBo.setPhone(bizInfo.get("phone"));
			checkoutInputBo.setAddress(bizInfo.get("address"));
			checkoutInputBo.setRemark(bizInfo.get("remark"));
			String json = bizInfo.get("cartItems");
			List<ShoppingCartItemInputBo> cartItems = JsonUtils.toObjectArray(json, ShoppingCartItemInputBo.class);
			checkoutInputBo.setCartItems(cartItems);
			rtnInfo = orderByMerchantApiService.generateOrder(checkoutInputBo);
		}

		logger.debug("执行时间：{}", System.currentTimeMillis() - time);
		return rtnInfo;
	}

	@Override
	public String getUrlMappingPath() {
		return "/h5/merchant/order/**";
	}

	@Override
	public boolean isCheckUserToken() {
		return true;
	}

}
